package com.roberto.entities;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.math.Rectangle;
import com.roberto.main.Main;

public class UFO extends Entity {
    protected Sprite UFOsprite;
    private static Sound sound1 = Gdx.audio.newSound(Gdx.files.internal("res/sounds/ufo2.wav"));
    private Sound ufoDestroyed;
    private boolean soundPlaying;

    public UFO() {
        UFOsprite = new Sprite(Main.megaTexture, 1, 1, 124, 53);
        ufoDestroyed = Gdx.audio.newSound(Gdx.files.internal("res/sounds/killUFO.wav"));
        width = UFOsprite.getWidth();
        height = UFOsprite.getHeight();
        pushToRandomX();
        y = 670;
        UFOsprite.setPosition(x, y);
    }

    public void destroy() {
        Invader.invExplosion.setPosition(x, y);
        Invader.invExplosion.setSize(width, height);
        destroyed = true;
        ufoDestroyed.play(0.8f);
        pushToRandomX();
        UFOsprite.setPosition(x, y);
    }

    public void update(float delta) {
        if (onGameField()) {
            if (!soundPlaying) {
                sound1.loop(0.2f);
                soundPlaying = true;
            }
        } else if (x + width > 0) {
            pushToRandomX();
        } else {
            stopSound();
            soundPlaying = false;
        }
        x += 130 * Gdx.graphics.getDeltaTime();
        UFOsprite.setPosition(x, y);

    }

    public boolean onGameField() {
        return x < Main.WIDTH && x + width > 0;
    }

    public final Sprite getSprite() {
        return UFOsprite;
    }

    public final Rectangle getBounds() {
        return UFOsprite.getBoundingRectangle();
    }

    private void pushToRandomX() {
        x = (float) (-2500 - ((Math.random() * 1500f)));
    }

    public static void stopSound() {
        sound1.stop();
    }

}
